import random
from datetime import  timedelta
from flask import Blueprint,jsonify,g
from flask_restful import Api,Resource, reqparse,marshal
from models.model import *
from models import db

book_bp = Blueprint('book',__name__,url_prefix='/book')
api = Api(book_bp)


class BookView(Resource):
    def get(self):
        book_ = Books.query.filter_by().all()
        book_data = []
        for i in book_:
            auther_ = Authers.query.filter_by(aid=i.book_auther).first()
            book = {
                'bid': i.bid,
                'book_name': i.book_name,
                'book_auther': auther_.name,
                'book_publicate_time': i.book_publicate_time,
                'book_price': i.book_price,
                'auther_id': auther_.aid,
                'pen_name': auther_.pen_name
            }
            book_data.append(book)
        return jsonify(data=book_data, code=200, msg='获取成功')


class AutherView(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('aid')
        args = parser.parse_args()
        aid = args.get('aid')
        auther_ = Authers.query.filter_by(aid=aid).first()
        if not auther_:
            return jsonify(code=204, msg='没有该作者')
        book_ = Books.query.filter_by(book_auther=auther_.aid).all()
        book_data = []
        for i in book_:
            book = {
                'name': auther_.name,
                'pen_name': auther_.pen_name,
                'book_name': i.book_name,
                'bid': i.bid
            }
            book_data.append(book)
        return jsonify(data=book_data, code=200, msg='获取成功')


api.add_resource(BookView, '/bookView')
api.add_resource(AutherView, '/autherView')

